<template>
  <div>
    <el-button type="primary" @click="handleAddUser">添加用户</el-button>
    <el-input
      v-model="input"
      style="width: 240px; margin-left: 20px;"
      :prefix-icon="Search"
      placeholder="请输入姓名"
      @keyup.enter="search"
    />
    <el-button type="info" plain @click="reset">重置</el-button>
    <el-table v-if="active" :data="filteredItems" style="width: 100%; margin-top: 20px" border :table-layout="'fixed'">
      <el-table-column prop="id" label="用户ID" width="100" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="name" label="真实姓名" />
      <el-table-column prop="sex" label="性别" width="80">
        <template #default="scope">
          {{ scope.row.sex === 'M' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="birthday" label="生日" width="120">
        <template #default="scope">
          {{ scope.row.birthday.slice(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话号码" width="120" />
      <el-table-column prop="email" label="电子邮箱" />
      <el-table-column prop="create_at" label="创建时间">
        <template #default="scope">
          {{ scope.row.create_at.slice(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色" width="100"/>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px"
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
    />
    <el-dialog v-model="dialogVisible" title="添加用户" width="50%">
      <el-form :model="formModel" :rules="formRules" ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formModel.username" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formModel.password" type="password" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="name">
              <el-input v-model="formModel.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formModel.sex">
                <el-radio value="M">男</el-radio>
                <el-radio value="F">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="formModel.birthday" type="date" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话号码" prop="phone">
              <el-input v-model="formModel.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="formModel.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="formModel.role" style="width: 100%">
                <el-option label="普通用户" value="user" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="50%">
      <el-form :model="editFormModel" :rules="formRules" ref="editForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editFormModel.username" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="name">
              <el-input v-model="editFormModel.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="editFormModel.sex">
                <el-radio value="M">男</el-radio>
                <el-radio value="F">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="editFormModel.birthday" type="date" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电话号码" prop="phone">
              <el-input v-model="editFormModel.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="editFormModel.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="editFormModel.role" style="width: 100%">
                <el-option label="普通用户" value="user" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUser, updateUser, deleteUser } from '@/api/userManage'
import { register } from '@/api/login'
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'; // 导入 day.js

const userList = ref([])
const total = ref(0)
const pageSize = ref(10)
const active = ref(true)

const input = ref('')

// 搜索
async function search() {
  currentPage.value = 1
  const res = await getUser({ name: input.value.trim() })
  userList.value = res.data
  total.value = res.data?.length
}

// 重置
function reset() {
  input.value = ''
  fetchUsers()
}

// 获取用户列表
const fetchUsers = async (data) => {
  // TODO: 调用API获取用户数据
  const res = await getUser(data)
  if (res.status) {
    ElMessage.error(res.msg)
    return
  }
  userList.value = res.data
  total.value = res.data?.length
}

// 添加用户
const dialogVisible = ref(false)

// 添加用户表单数据
const formModel = reactive({
  username: '',
  password: '',
  name: '',
  sex: 'M',
  birthday: '',
  phone: '',
  email: '',
  role: 'user'
})

// 重置表单函数
function resetForm() {
  // 直接修改表单模型的属性来重置
  formModel.username = '';
  formModel.password = '';
  formModel.name = '';
  formModel.sex = 'M';
  formModel.birthday = '';
  formModel.phone = '';
  formModel.email = '';
  formModel.role = 'user';
}

const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名必须是4~20位字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*[0-9]).{6,15}$/, message: '密码必须为6~15位字母、数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const handleAddUser = () => {
  dialogVisible.value = true
}

// 添加用户
const submitForm = async () => {
  try {
    const birthday_format = dayjs(formModel.birthday).format('YYYY-MM-DD'); // 格式化后的日期
    const response = await register({
        name: formModel.name,
        sex: formModel.sex,
        birthday: birthday_format,
        phone: formModel.phone,
        email: formModel.email,
        username: formModel.username,
        password: formModel.password
    })
    if (!response.status) { 
      ElMessage.success('添加用户成功')
      dialogVisible.value = false
      resetForm()
      fetchUsers()
    } else {
      ElMessage.error(response.msg)
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('添加用户失败')
  }
  resetForm()
}

// 编辑用户
const editDialogVisible = ref(false)
const editFormModel = ref({
  id: '',
  username: '',
  name: '',
  sex: 'M',
  birthday: '',
  phone: '',
  email: '',
  role: 'user'
})

// 编辑用户
const handleEdit = (user) => {
  editFormModel.value = {
    id: user.id,
    username: user.username,
    name: user.name,
    sex: user.sex,
    birthday: user.birthday,
    phone: user.phone,
    email: user.email,
    role: user.role
  }
  editDialogVisible.value = true
}

// 更新用户
const submitEditForm = async () => {
  try {
    const birthday_format = dayjs(editFormModel.value.birthday).format('YYYY-MM-DD'); // 格式化后的日期
    const res = await updateUser({
      id: editFormModel.value.id,
      username: editFormModel.value.username,
      name: editFormModel.value.name,
      sex: editFormModel.value.sex,
      birthday: birthday_format,
      phone: editFormModel.value.phone,
      email: editFormModel.value.email,
      role: editFormModel.value.role
    })
    if (res.status) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success('更新用户成功')
    editDialogVisible.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error('更新用户失败')
  }
}

// 删除用户
const handleDelete = (row) => {
  handleDeleteUser(row.id)
}

// 删除用户
const handleDeleteUser = async (userId) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await deleteUser({ id: userId })
    if (res.status) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success('删除用户成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败')
    }
  }
}

// 分页
const handlePageChange = (page) => {
  fetchUsers({ page: page - 1 })
}
// 当前页默认为1
const currentPage = ref(1)
// 过滤后的数据
const filteredItems = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    return userList.value.slice(start, start + pageSize.value); // 根据当前页和每页条数获取数据
})

onMounted(() => {
  active.value = true
  fetchUsers()
})

onBeforeUnmount(() => {
  active.value = false
})
</script>
